﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using School.Common;
using School.Entities;
using School.Accounting;

namespace School.Pages.Accounting
{
    public partial class ExpenseEditor : System.Web.UI.Page
    {
        DataTable dt;
        int tempid = 1;
        int id = 0;
        protected void Page_Load(object sender, EventArgs e)
        {
            if ((IQueryable<int>)Session["privilage"] != null)
            {
                var x = (IQueryable<int>)Session["privilage"];

                if (x.Contains(101) == true)
                {
                    long id = 0;

                    IEnumerable<long> ecampuses = new List<long>();
                    IEnumerable<long> ecertificates = new List<long>();
                    IEnumerable<long> estages = new List<long>();
                    IEnumerable<long> egrades = new List<long>();

                    if (!IsPostBack)
                        Session["Payments"] = null;

                    if (Request.QueryString["Id"] != "" && long.TryParse(Request.QueryString["Id"], out id) && !IsPostBack)
                    {
                        ecampuses = Expense.GetCampusesIds(id);
                        ecertificates = Expense.GetCertificatesIds(id);
                        estages = Expense.GetStagesIds(id);
                        egrades = Expense.GetGradesIds(id);
                    }

                    var campuses = Structure.GetCampuses();
                    var certificates = Structure.GetCertificates();
                    var stages = Structure.GetStages();
                    var grades = Structure.GetGrades();

                    string html = "<ul id='TreeView' class='filetree'>";

                    string chkd = "checked";

                    foreach (ORG_Campus campus in campuses)
                    {
                        if (ecampuses.Contains(campus.Id))
                            html += "<li><input type='checkbox' name='campuses' value='" + campus.Id + "' " + chkd + " /><lable for='campuses'>" + campus.Name + "</lable></li>";
                        else
                            html += "<li><input type='checkbox' name='campuses' value='" + campus.Id + "' /><lable for='campuses'>" + campus.Name + "</lable></li>";

                        html += "<ul>";

                        foreach (ORG_Certificate certificate in certificates.Where(c => c.Campus_Id == campus.Id))
                        {
                            if (ecertificates.Contains(certificate.Id))
                                html += "<li><input type='checkbox' name='certificates' value='" + certificate.Id + "' " + chkd + " /><lable for='certificates'>" + certificate.Name + "</lable></li>";
                            else
                                html += "<li><input type='checkbox' name='certificates' value='" + certificate.Id + "' /><lable for='certificates'>" + certificate.Name + "</lable></li>";

                            html += "<ul>";

                            foreach (ORG_Stage stage in stages.Where(s => s.Certificate_Id == certificate.Id))
                            {
                                if (estages.Contains(stage.Id))
                                    html += "<li><input type='checkbox' name='stages' value='" + stage.Id + "' " + chkd + " /><lable for='stages'>" + stage.Name + "</lable></li>";
                                else
                                    html += "<li><input type='checkbox' name='stages' value='" + stage.Id + "' /><lable for='stages'>" + stage.Name + "</lable></li>";

                                html += "<ul>";

                                foreach (ORG_Grade grade in grades.Where(g => g.Stage_Id == stage.Id))
                                {
                                    if (egrades.Contains(grade.Id))
                                        html += "<li><input type='checkbox' name='grades' value='" + grade.Id + "' " + chkd + " /><lable for='grades'>" + grade.Name + "</lable></li>";
                                    else
                                        html += "<li><input type='checkbox' name='grades' value='" + grade.Id + "' /><lable for='grades'>" + grade.Name + "</lable></li>";
                                }

                                html += "</ul>";
                            }

                            html += "</ul>";
                        }
                        html += "</ul>";
                    }

                    html += "</ul>";

                    StructureTree.InnerHtml += html;

                    LstDepartments.DataSource = Expense.Departments();
                    LstDepartments.DataValueField = "Id";
                    LstDepartments.DataTextField = "Name";
                    LstDepartments.DataBind();

                    if (!IsPostBack & id > 0)
                    {

                    }
                }
                else
                    Response.Redirect("../organization/no_privelege.aspx");
            }
            else
                Response.Redirect("../organization/no_privelege.aspx");
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            string[] campuses = Request.Form["campuses"] != null ? Request.Form["campuses"].Split(",".ToCharArray()) : null;
            string[] certificates = Request.Form["certificates"] != null ? Request.Form["certificates"].Split(",".ToCharArray()) : null;
            string[] stages = Request.Form["stages"] != null ? Request.Form["stages"].Split(",".ToCharArray()) : null;
            string[] grades = Request.Form["grades"] != null ? Request.Form["grades"].Split(",".ToCharArray()) : null;

            ACC_Expense ex = new ACC_Expense();
            
            ex.Name = TxtName.Text; 
            ex.Code = TxtCode.Text; 
            ex.Detail = TxtDetail.Text; 
            ex.Department_Id = int.Parse(LstDepartments.SelectedValue); 
            ex.Enable_Discount = ChkDiscountable.Checked ? true : false; 
            ex.Flashback = byte.Parse(LstReturnOptions.SelectedValue);
            ex.Automatic_With_Services = ChkAutomatic.Checked ? true : false; 
            
            if(TxtRValue.Text != "")
                ex.Flashback_Value = decimal.Parse(TxtRValue.Text);

            ex.Transaction_Returnable_type = byte.Parse(LstTransactionOption.SelectedValue); 

            if(TxtTValue.Text !="")
                ex.Transaction_Returnable_Value = decimal.Parse(TxtTValue.Text);
            
            DataTable payments;

            if (Session["Payments"] != null)
                payments = (DataTable)(Session["Payments"]);
            else
                payments = null;

            Expense.Add(ex,campuses,certificates,stages,grades,payments);

            Session["Payments"] = null;

            Response.Redirect("Expenses.aspx");
        }

        protected void Button2_Click(object sender, EventArgs e)
        {


            if (Session["Payments"] != null)
                dt = (DataTable)(Session["Payments"]);
            else
            {
                dt = new DataTable();
                dt.Columns.Add("id", typeof(int));
                dt.Columns["id"].AllowDBNull = false;
                dt.Columns["id"].Unique = true;

                dt.Columns.Add("التاريخ", typeof(string));
                dt.Columns.Add("القيمة", typeof(decimal));
            }

            DataRow row = dt.NewRow();
           
            if (dt.Rows.Count != 0)
            {
                for (int i = 0; i < dt.Rows.Count ; i++)
                {
                    id = tempid + 1;
                    tempid = id;
                }

            }
            else
            {
                id = 1;
            }

            row[0] = id;
            row[1] = TxtDate.Text;
            row[2] = decimal.Parse(TxtValue.Text);

            dt.Rows.Add(row);

            GridView1.DataSource = dt;
            GridView1.DataBind();

            TxtDate.Text = "";
            TxtValue.Text = "";

            Session["Payments"] = dt;

        }

        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if(Session["Payments"] == null)
            {
                return;
            }

            dt = (DataTable)(Session["Payments"]);

            if (e.CommandName == "delete")
            {
                GridViewRow selectedrow = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer;
                DataKey id = GridView1.DataKeys[selectedrow.RowIndex];
                dt.Rows[selectedrow.RowIndex].Delete();
            }

            Session["Payments"] = dt;
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            e.Row.Cells[1].Visible = false;
        }

        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            dt = (DataTable)Session["Payments"];
            DataRow dr = dt.Rows[e.RowIndex];
            dr.Delete();
            Session["Payments"] = dt;
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
    }
}